package org.example.ssh

import net.schmizz.sshj.SSHClient
import org.example.ssh.base.executeCmdPrint

class DeployDocker {
    var workDir = "/home/docker-images"
    val dockerVersion = "20.10.21"
    val sourceRegistry = "https://download.docker.com"
    val mirrorRegistry = "https://mirrors.aliyun.com/docker-ce"

    suspend fun setupDockerSource(ssh: SSHClient) {
        // 添加Docker官方GPG密钥
        executeCmdPrint(ssh, "curl -fsSL ${sourceRegistry}/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg")
        
        // 设置Docker源
        executeCmdPrint(ssh, """echo \
  "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] ${sourceRegistry}/linux/ubuntu \
  \$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null""")
        
        // 更新apt包索引
        executeCmdPrint(ssh, "sudo apt-get update")
    }
    
    suspend fun setupDockerMirror(ssh: SSHClient) {
        // 使用阿里云镜像源
        executeCmdPrint(ssh, "sudo mkdir -p /etc/docker")
        executeCmdPrint(ssh, """sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://registry.cn-hangzhou.aliyuncs.com"]
}
EOF""")
        executeCmdPrint(ssh, "sudo systemctl daemon-reload")
    }

    suspend fun installDocker(ssh: SSHClient) {
        // 安装指定版本的Docker
        executeCmdPrint(ssh, "sudo apt-get install -y docker-ce=${dockerVersion} docker-ce-cli=${dockerVersion} containerd.io")
        
        // 启动并启用Docker服务
        executeCmdPrint(ssh, "sudo systemctl start docker")
        executeCmdPrint(ssh, "sudo systemctl enable docker")
        
        // 将当前用户添加到docker组
        executeCmdPrint(ssh, "sudo usermod -aG docker ")
    }
    
    suspend fun pullImages(ssh: SSHClient, images: List<String>) {
        for (image in images) {
            executeCmdPrint(ssh, "docker pull $image")
        }
    }
    
    suspend fun deploy(ssh: SSHClient) {
        // 设置Docker源
        setupDockerSource(ssh)
        
        // 安装指定版本的Docker
        installDocker(ssh)
        
        // 设置Docker镜像加速器
        setupDockerMirror(ssh)
        
        // 拉取需要的镜像
//        val images = listOf(
//            "redis:6.2.10",
//            "mysql:8.0",
//            "nginx:latest"
//        )
//        pullImages(ssh, images)
        
        println("Docker部署完成")
    }
}
